﻿using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nb.Common.NHibernates;
using Nb.Tenants.Libs.Domains.Models;
using Nb.Tenants.Libs.Infrastructures;
using NHibernate;

namespace Nb.Tenants.Libs
{
    //对于带有 AssemblyInitialize 属性标记的方法，仅当该方法属于带有 TestClass 属性标记的类的成员时，测试引擎才会运行它
    [TestClass]
    public class SchemaTest
    {
        private static bool _inited = false;
        [AssemblyInitialize]
        public static void SetupTestEnvForEachClass(TestContext context)
        {
            Debug.WriteLine("Assembly Init => ");
            if (_inited)
            {
                return;
            }

            const string dbName = "TenantsDbTest";
            //NHibernateProfiler.Initialize();
            //生成数据库结构
            SqlUtHelper.Instance = new MyUtHelper(dbName);
            SqlUtHelper.Instance.ReCreateDbIfExist(".", dbName, "sa", "zqnb_123");

            //更灵活的安装脚本，应该手工指定
            //TODO...
            //如果模块数据库要随打包程序自动安装，
            //则模块的Map必须经过单元测试，然后将被用在打包程序生成数据库的逻辑里。
       
            var libs = new Type[] {typeof(TenantMap)};

            SqlUtHelper.Instance.SetUpNHibernate(true, libs);
            _inited = true;
        }

        [AssemblyCleanup]
        public static void AssemblyCleanup()
        {
            Debug.WriteLine("Assembly Cleanup => ");
        }
        
        [TestMethod]
        public void MakeSchemaTest()
        {
            //var enumerable = Enumerable.Range(1, 10);
            //var dateDemos = enumerable.Select(x => new DateDemo() {Count =x, DateTime = new DateTime(2000, 1, 12 -x)});
            //var query = dateDemos.AsQueryable();
            //query = query.OrderBy(x => x.Count);
            //query = query.OrderByDescending(x => x.DateTime);
            //var result = query.ToList();

            //测试
            ISession session = SqlUtHelper.Instance.OpenSession();

            var user = new User();
            user.LoginName = "admin";
            session.Save(user);

            var user2 = new User();
            user2.LoginName = "admin2";
            user2.TenantId = new TenantId("abc");
            session.Save(user2);

            session.Flush();
        }
    }
}